package com.gs.m_login

import android.content.Context
import android.util.Log
import com.gs.common.API
import com.gs.common.callback.HttpCallback
import com.gs.common.constant.HttpCode
import com.gs.common.constant.StateCode
import com.gs.common.global.GlobalVariables
import com.gs.common.sqlite.UserSqliteOpenHelper
import com.gs.common.data.User
import okhttp3.Call
import okhttp3.Response
import org.json.JSONObject
import java.net.ConnectException
import java.net.SocketTimeoutException

class LoginModel(context: Context){

    private val api by lazy { API() }
    private val userSqliteOpenHelper by lazy { UserSqliteOpenHelper(context) }

//    fun checkUserState(usernameOrPhoneNum: String, block: (Int) -> Unit) {
//        block.invoke(STATE_EXIST)
//        block.invoke(STATE_NOT_EXIST)
//    }

    fun login(usernameOrPhoneNum: String, password: String, block: (Int) -> Unit){
        block.invoke(StateCode.STATE_LOADING)
        api.login(usernameOrPhoneNum, password, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.headers("Set-Cookie")
                Log.d("cookies", "$cookies")
                Log.d("result", result)
                val resultJSON = JSONObject(result)
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    for (cookie in cookies) {
                        if (cookie.contains("token=")) {
                            val token = cookie.replace("token=", "")
                            GlobalVariables.token = token
                            val username = if (resultJSON["username"].toString() == "null"){
                                ""
                            } else {
                                resultJSON["username"].toString()
                            }
                            val nickname = if (resultJSON["nickname"].toString() == "null"){
                                "用户123"
                            } else {
                                resultJSON["nickname"].toString()
                            }
                            val user = User(userName = username,
                                    nickname = nickname,
                                    token = token)
                            Log.d("user", "$user")
                            GlobalVariables.loginUser = user
                            val loginUsers = userSqliteOpenHelper.selectUser()
                            if (loginUsers.isEmpty()) {
                                userSqliteOpenHelper.addUser(user)
                            } else {
                                block.invoke(StateCode.STATE_FAILED)
                                return
                            }
                            break
                        }
                    }
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when(e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }
                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }
                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }
        })
    }

    companion object {
        const val STATE_NOT_EXIST = 0
        const val STATE_EXIST = 1

        private var instance: LoginModel? = null
        fun getInstance(context: Context): LoginModel {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = LoginModel(context)
                    }
                }
            }
            return instance!!
        }
    }
}